# -*- coding: utf-8 -*-
from openerp.osv import fields,osv
from openerp import tools
from openerp.tools.translate import _
from openerp.modules.registry import RegistryManager
from datetime import datetime,timedelta
from openerp.tools import DEFAULT_SERVER_DATE_FORMAT as DATE_FORMAT
import datetools
from dateutil.relativedelta import relativedelta

class pm_meter_category(osv.osv):
    _name = 'pm.meter.category'
    _columns = {
        'name':fields.char(string='类别名称',size=100,required=True),
        'code':fields.char(string='类别代码',size=100,required=True),
        'cost_item_id':fields.many2one('pm.cost.item',domain="[('billing_type','=','meter_reading')]",string='收费项目'),
        'remark':fields.text(string='备注'),
    }
pm_meter_category()

class pm_meter(osv.osv):
    _name = 'pm.meter'

    def on_change_meter_category(self,cr,uid,ids,category_id,context=None):
        print 'on_change_meter_category %s' % category_id
        value = {}
        if not category_id:
            return value
        category_item = self.pool.get('pm.meter.category').read(cr,uid,category_id,['cost_item_id'],context=context)
        print 'category_item is %s' % category_item
        if category_item:
            values = {
                'cost_item_id':category_item['cost_item_id'][0],
            }
        return {'value':values}

    _columns = {
        'category_id':fields.many2one('pm.meter.category',string='表计类别',required=True),
        'cost_item_id':fields.related('category_id','cost_item_id',type='many2one',relation='pm.cost.item',string='收费项目',readonly='True'),
        'project_id':fields.many2one('pm.project',string='所属管理处'),
        'area_id':fields.many2one('pm.project.area',string='所属区域',domain="[('project_id','=',project_id)]"),
        'building_id':fields.many2one('pm.project.building',string='所属楼栋',help='Building',domain="[('project_area_id','=',area_id)]"),
        'room_id':fields.many2one('pm.project.building.room',string='所属房间',required=True,domain="[('building_id','=',building_id)]"),
        'name':fields.char(string='表号',size=100,required=True),
        'specification':fields.char(string='规格',size=100,required=False),
        'init_value':fields.float(string='安装读数',required=True),
        'asset_no':fields.char(string='资产号',size=100,required=False),
        'installed_date':fields.date(string='安装日期'),
        'factory':fields.char('生产厂家',size=100),
        'rate':fields.float('倍率'),
        'stop_date':fields.date(string='报停日期'),
        'range':fields.float(string='量程'),
        'meter_reader':fields.char(string='抄表员',size=100),
        'meter_book':fields.char(string='所属抄表本',size=100),
        'meter_order':fields.integer(string='抄表顺序号'),
        'state':fields.selection([('normal','正常'),('hasstopped','报停')],string='状态'),
        'remark':fields.text(string='备注'),
    }
pm_meter()

class pm_meter_record(osv.osv):
    _name = 'pm.meter.record'

    def on_change_meter(self,cr,uid,ids,meter_id,context=None):
        print 'call get_date_by_adddays %s' % datetools.get_date_by_addday('2014-10-10',1)
        values = {}
        if meter_id:
            meter = self.pool.get('pm.meter').read(cr,uid,meter_id,context=context)
            print meter['rate']
            if meter:
                values = {
                    'meter_rate':meter['rate'],
                    'start_value':meter['init_value'],
                    'last_date':meter['installed_date']
                }
            record_ids = self.search(cr,uid,[('meter_id','=',meter_id)],order='input_time desc',limit=1,context=context)
            if record_ids:
                record = self.browse(cr,uid,record_ids[0],context=context)
                print type(record.current_date),DATE_FORMAT
                if record:
                    values = {
                        'start_value':record.end_value,
                        'last_date':record.current_date, #datetools.get_date_by_addday(record.current_date,1),
                        'current_date':datetools.get_next_date(record.current_date,record.cost_item_id.unit_of_period,record.cost_item_id.charge_period),
                        #'last_date': datetime.strftime(datetime.strptime(record.current_date,DATE_FORMAT)+timedelta(days=1),'%Y-%m-%d'),
                    }
        return {'value':values}

    def on_change_calculate(self,cr,uid,ids,start_value,end_value,value,context=None):
        value = end_value - start_value
        return {'value':{
            'value':value
        }}

    def check_currentdate(self,cr,uid,ids,context=None):
        for item in self.browse(cr,uid,ids,context=context):
            if datetime.strptime( item.last_date,DATE_FORMAT) >= datetime.strptime(item.current_date,DATE_FORMAT):
                return False
        return True

    def check_value(self,cr,uid,ids,context=None):
        for item in self.browse(cr,uid,ids,context=context):
            if item.end_value<item.start_value:
                return False
        return True

    def create_receivable(self,cr,uid,item,context):
        print 'item.cost_item_id.unit_of_period %s' % item.cost_item_id.unit_of_period
        print 'item.current_date is %s' % item.current_date
        billing_start_date = datetime.strptime(item.last_date,DATE_FORMAT) + relativedelta(days=+1)
        billing_start_date = datetime.strftime(billing_start_date,DATE_FORMAT)
        rev_item = {
            'project_id':item.project_id.id,
            'area_id':item.area_id.id,
            'building_id':item.building_id.id,
            'room_id':item.room_id.id,
            'cost_item_id':item.cost_item_id.id,
            'start_value':item.start_value,
            'end_value':item.end_value,
            'count':item.value,
            'price':item.cost_item_id.price,
            'rate':item.meter_id.rate,
            'amount':item.cost_item_id.price * item.value * item.meter_id.rate,
            'billing_start_date':billing_start_date,#datetools.get_date_by_addday(item.last_date,1),
            'billing_end_date':item.current_date,
            'meter_record_id':item.id,
            'partner_id':item.room_id.hourseholder.id,
        }
        print 'rev_item is %s' % rev_item
        context['meter'] = True
        return self.pool.get('pm.cost.receivable').create(cr,uid,rev_item,context=context)

    def bt_check(self,cr,uid,ids,context=None):
        for item in self.browse(cr,uid,ids,context=context):
            self.write(cr,uid,ids,{'state':'checked','check_man':uid,'check_time':datetime.now()},context=context)
            print 'meter record check item is %s' % item
            self.create_receivable(cr,uid,item,context)
        return True

    #def bt_uncheck(self,cr,uid,ids,context=None):
    #    for item in self.browse(cr,uid,ids,context=context):
    #        self.write(cr,uid,ids,{'check_man':uid,'check_time':datetime.now()},context=context)
    #        #TODO add shoud received item in cost 
    #    return True

    def write(self,cr,uid,ids,data,context=None):
        for item in self.read(cr,uid,ids,['state'],context=None):
            if item['state'] == 'checked' and data['state']!='received':
                raise osv.except_osv(_("修改失败"),_("只能修改未经审核的抄表记录!"))
        return super(pm_meter_record,self).write(cr,uid,ids,data,context=context)

    def unlink(self,cr,uid,ids,context=None):
        for item in self.read(cr,uid,ids,['state'],context=None):
            if item['state'] != 'recorded':
                raise osv.except_osv(_("删除失败"),_("只能删除未经审核的抄表记录!"))
        return super(pm_meter_record,self).unlink(cr,uid,ids,context=context)

    def create(self,cr,uid,data,context=None):
        room_id = data['room_id']
        meter_category_id = data['meter_category_id']
        cost_item_id = self.pool.get('pm.meter.category').browse(cr,uid,meter_category_id,context=context).cost_item_id.id
        if not self.pool.get('pm.cost.item.room').search(cr,uid,[('room_id','=',room_id),('cost_item_id','=',cost_item_id)],context=context):
            raise osv.except_osv(_('收费项未设置'),_('不能增加抄表记录，因为此房间没有设置此收费项!'))
        id = super(pm_meter_record,self).create(cr,uid,data,context=context)
        return id
        
    _columns = {
        'project_id':fields.many2one('pm.project',string='所属管理处'),
        'area_id':fields.many2one('pm.project.area',string='所属区域',domain="[('project_id','=',project_id)]"),
        'building_id':fields.many2one('pm.project.building',string='所属楼栋',help='Building',domain="[('project_area_id','=',area_id)]"),
        'room_id':fields.many2one('pm.project.building.room',string='所属房间',required=True,domain="[('building_id','=',building_id)]"),
        'name':fields.related('room_id','name',type='char',string='房间编号'),
        'meter_category_id':fields.many2one('pm.meter.category',string='表计类别',required=True),
        'cost_item_id':fields.related('meter_category_id','cost_item_id',type='many2one',relation='pm.cost.item',string='收费项目',readonly='True'),
        'meter_id':fields.many2one('pm.meter',string='表号',required=True),
        'meter_rate':fields.related('meter_id','rate',type='float',string='倍率'),
        'start_value':fields.float(string='起数'),
        'end_value':fields.float(string='止数'),
        'value':fields.float(string='用量'),
        'last_date':fields.date(string='上次抄表日期'),
        'current_date':fields.date(string='本次抄表日期'),
        'input_time':fields.datetime(string='输入时间'),
        'register_date':fields.date(string='登记日期'),
        'record_type':fields.char(string='抄表方式',size=100),
        'record_man':fields.char(string='抄表员',size=100),
        'state':fields.selection([('recorded','已录入'),('checked','已审核'),('received','已收费')],string='状态'),
        'check_man':fields.many2one('res.users',string='审核人'),
        'check_time':fields.datetime(string='审核时间'),
        'remark':fields.text(string='备注'),
    }
    
    _defaults = {
        'state':lambda self,cr,uid,ids:'recorded',
        'current_date': lambda self,cr,uid,ids: datetime.strftime(datetime.today(),DATE_FORMAT),
        'register_date': lambda self,cr,uid,ids: datetime.strftime(datetime.today(),DATE_FORMAT),
        'input_time':lambda self,cr,uid,ids: datetime.strftime(datetime.now(),'%Y-%m-%d %H:%M:%S')
    }
    _constraints = [
        (check_currentdate,'上次抄表日期必须小于本次抄表日期！',['last_date','current_date']),
        (check_value,'止数必须大于起数!',['start_value','end_value']),
    ]
pm_meter_record()

